package top.broncho.gank.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import com.cxz.multiplestatusview.MultipleStatusView
import top.broncho.gank.R
import top.broncho.gank.adapter.ShareAdapter
import top.broncho.gank.app.App
import top.broncho.gank.bean.Article
import top.broncho.gank.bean.ShareResponseBody
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.ActivityShareBinding
import top.broncho.gank.ext.showSnackMsg
import top.broncho.gank.utils.DialogUtil
import top.broncho.gank.utils.NetWorkUtil
import top.broncho.gank.widget.SpaceItemDecoration
import top.broncho.gank.widget.SwipeItemLayout
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import kotlinx.android.synthetic.main.toolbar.*
import org.jetbrains.anko.toast
import top.broncho.mvvm.base.BaseVMActivity

/**
 * @author chenxz
 * @date 2019/11/15
 * @desc 我的分享
 */
class ShareActivity : BaseVMActivity<ActivityShareBinding>() {
    private val viewModel by viewModels<ShareViewModel> { viewModelFactory }
    private var pageSize = 20

    private var isRefresh = true

    private val datas = mutableListOf<Article>()
    private var mLayoutStatusView: MultipleStatusView? = null

    private val shareAdapter: ShareAdapter by lazy {
        ShareAdapter(datas)
    }

    fun showLoading() {
        // swipeRefreshLayout.isRefreshing = isRefresh
    }

    fun hideLoading() {
        swipeRefreshLayout?.isRefreshing = false
        if (isRefresh) {
            shareAdapter.setEnableLoadMore(true)
        }
    }

    fun showError(errorMsg: String) {
        mLayoutStatusView?.showError()
        if (isRefresh) {
            shareAdapter.setEnableLoadMore(true)
        } else {
            shareAdapter.loadMoreFail()
        }
    }

    override fun getLayoutId(): Int = R.layout.activity_share

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initView()
        viewModel.shareList.observe({ lifecycle }) {
            if (it.isFailure) {
                showError(it.exceptionOrNull().toString())
                return@observe
            }
            mLayoutStatusView?.showContent()
            showShareList(it.getOrThrow())
        }
        if (viewModel.shareList.value == null) {
            start()
        }
        viewModel.deleteShareArticle.observe({ lifecycle }) {
            showDeleteArticle(it.isSuccess)
        }
        viewModel.collect.observe({ lifecycle }) {
            showCollectSuccess(it.isSuccess)
        }
        viewModel.cancel.observe({ lifecycle }) {
            showCancelCollectSuccess(it.isSuccess)
        }
    }

    fun initView() {
        mLayoutStatusView = multiple_status_view
        toolbar.run {
            title = getString(R.string.my_share)
            setSupportActionBar(this)
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }

        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager =
                LinearLayoutManager(this@ShareActivity)
            adapter = shareAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ShareActivity))
            addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(this@ShareActivity))
        }
        shareAdapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            onItemClickListener = this@ShareActivity.onItemClickListener
            onItemChildClickListener = this@ShareActivity.onItemChildClickListener
        }
    }

    fun start() {
        mLayoutStatusView?.showLoading()
        viewModel.getShareList(1)
    }

    fun showShareList(body: ShareResponseBody) {
        body.shareArticles.datas.let {
            shareAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                pageSize = body.shareArticles.size
                if (body.shareArticles.over) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (shareAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    fun showDeleteArticle(success: Boolean) {
        if (success) {
            toast(getString(R.string.share_article_delete))
        }
    }

    fun showCollectSuccess(success: Boolean) {
        if (success) {
            toast(resources.getString(R.string.collect_success))
        }
    }

    fun showCancelCollectSuccess(success: Boolean) {
        if (success) {
            toast(resources.getString(R.string.cancel_collect_success))
        }
    }

    /**
     * RefreshListener
     */
    private val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        shareAdapter.setEnableLoadMore(false)
        viewModel.getShareList(1)
    }

    /**
     * LoadMoreListener
     */
    private val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        val page = shareAdapter.data.size / pageSize + 1
        viewModel.getShareList(page)
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas.isNotEmpty()) {
            val data = datas[position]
        }
    }

    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
        BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            if (!NetWorkUtil.isNetworkAvailable(App.context)) {
                showSnackMsg(resources.getString(R.string.no_network))
                return@OnItemChildClickListener
            }
            if (datas.isNotEmpty()) {
                val data = datas[position]
                when (view.id) {
                    R.id.rl_content -> {
                        ContentActivity.start(this, data.id, data.title, data.link)
                    }
                    R.id.iv_like -> {
                        if (isLogin) {
                            val collect = data.collect
                            data.collect = !collect
                            shareAdapter.setData(position, data)
                            if (collect) {
                                viewModel.cancelCollectArticle(data.id)
                            } else {
                                viewModel.addCollectArticle(data.id)
                            }
                        } else {
                            Intent(this, LoginActivity::class.java).run {
                                startActivity(this)
                            }
                            toast(resources.getString(R.string.login_tint))
                        }
                    }
                    R.id.btn_delete -> {
                        DialogUtil.getConfirmDialog(this,
                            resources.getString(R.string.confirm_delete),
                            DialogInterface.OnClickListener { _, _ ->
                                viewModel.deleteShareArticle(data.id)
                                shareAdapter.remove(position)
                            }).show()
                    }
                }
            }
        }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_share, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.action_add -> {
                Intent(this@ShareActivity, CommonActivity::class.java).run {
                    putExtra(Constant.TYPE_KEY, Constant.Type.SHARE_ARTICLE_TYPE_KEY)
                    startActivity(this)
                }
            }
        }
        return super.onOptionsItemSelected(item)
    }

}